import 'dart:io';
import 'package:flutter_hsh/fluttergromore/config/app_const.dart';
import '../http/http_utils.dart';
import '../http/response_model/response_model.dart';
import '../plugin/ts_plugin.dart';
import '../usersp/user_sp.dart';
import '../utils/device_package_info.dart';
import '../../utils/k_log.dart';
import 'api.dart';
import 'bean/config_bean.dart';
import 'bean/cookbook_bean.dart';
import 'bean/free_bean.dart';
import 'bean/product_info_bean.dart';
import 'bean/recipe_search_bean.dart';

class ApiService {
  ///行为上报
  Future appReport({
    required int actionType,
    required String adId,
    required String placementId,
    required int adStyle,
    String ecpm = "0",
    String adPlatForm = "",
  }) async {
    var appId = (await UserSp.instance.getAppConfig())?.appId ?? "";
    var info = DevicePackageInfo();
    Map<String, Object> map = {
      //行为类型, 0:展示、1:点击 2请求
      "actionType": actionType,
      //代码位id
      "adId": adId,
      //广告位id
      "placementId": placementId,
      //0:信息流、1:全屏、2:插屏、3:激励视频、4:开屏、5:banner广告
      "adStyle": adStyle,
      //广告平台(可为空字符串、不能为空)、例：ks、oppo、csj(穿山甲)、bqt(百度)
      "adPlatForm": adPlatForm,
      //APP唯一标识
      "appId": appId,
      //
      "appName": await info.getAppName,
      "appVersion": await info.getAppVersion(),
    };
    var djId = await UserSp.instance.getDjid();
    if (djId != null && djId.isNotEmpty) {
      map["djId"] = djId;
      map["ecpm"] = ecpm;
      map["pkgName"] = Platform.isIOS
          ? "com.weather.quickly.report.pg"
          : await info.getPackageName();
      map["revenue"] = 0;
      //map["deviceIp"] = await UserSp.instance.getAddressIP(); //设备IP
      map["adChainId"] = ""; //广告组链ID
      map["sceneDetail"] = ""; //广告组链ID
      map["scene"] = "iapp"; // 应用内=iapp ; 应用外=oapp
      map["appVersion"] = await info.getAppVersion();
    }
    KLog.d("行为上报 ${map.toString()}");
    var result = await HttpUtils.post(
      Api.appReport,
      data: map,
    );
    return result;
  }

  ///加白名单
  Future<ResponseModel> addWhiteList(String password) async {
    var dInfo = DevicePackageInfo.instance;
    var map = {
      "password": password,
      "appVersion": await dInfo.getAppVersion(),
    };
    var djId = await UserSp.instance.getDjid();
    if (djId != null && djId.isNotEmpty) {
      map["djId"] = djId;
    }
    var result = await HttpUtils.post(
      Api.addWhiteList,
      data: map,
    );
    return result;
  }

  ///获取初始化信息
  Future<ResponseModel<ConfigBean>?> getAppConfig() async {
    var dInfo = DevicePackageInfo.instance;
    Map<String, String?> map = {
      "pkgName": Platform.isIOS
          ? "com.weather.quickly.report.pg"
          : await dInfo.getPackageName(),
      "version": await dInfo.getBuildNumber(),
      "appVersion": await dInfo.getAppVersion(),
      "channel": AppConst.channel,
    };
    var djId = await UserSp.instance.getDjid();
    if (djId != null && djId.isNotEmpty) {
      map["djId"] = djId;
    }
    var result = await HttpUtils.get(
      Api.appConfig,
      params: map,
      fromJsonT: (json) => ConfigBean.fromJson(json),
    );
    if (result.isSucceed) {
      //保存配置
      UserSp.instance.saveAppConfig(infoEntity: result.data);
    }
    return result;
  }

  ///获取初始化信息
  Future<ResponseModel<ConfigBean>?> appInstall() async {
    try {
      var appId = (await UserSp.instance.getAppConfig())?.appId ?? "";
      var dInfo = DevicePackageInfo.instance;
      Map<String, Object> map = {
        "appId": appId,
        "androidId": await dInfo.getId() ?? "",
        "appVersion": await dInfo.getAppVersion(),
        "pkgName": await dInfo.getPackageName(),
        //设备品牌
        "deviceBrand": await dInfo.getBrand() ?? "",
        //设备型号
        "deviceModel": await dInfo.getModel() ?? "",
        //"deviceIp": await TsPlugin.getIPAddress(),
        //"deviceIp6": await TsPlugin.getLocalIpV6(),
        //设备等级
        "deviceLevel": 1,
        //IOS广告标示符
        "idfa": "",
        //首次安装时间，时间戳（秒）
        "installDatetime":
            (DateTime.now().millisecondsSinceEpoch ~/ 1000).toInt(),

        ///匿名设备标识符
        "oaId": await UserSp.instance.getOaId(),
        "oaIdU": await UserSp.instance.getOaIdU(),
        "oaIdH": await UserSp.instance.getOaIdH(),

        //MAC地址
        "mac": await TsPlugin.getMacFromHardware(),
        //入网类型：0：WIFI、1：4G、2：5G
        "networkAccess": await TsPlugin.getNetworkType(),
        //操作系统, 0：Android、1：iOS 2.鸿蒙
        "os": await TsPlugin.getSystemCode(),
        if ((await TsPlugin.getSystemCode()) == 2)
          "idfv": await TsPlugin.getSystemVersion(),
        "resolution": "${await dInfo.widthPx()}x${await dInfo.heightPx()}",
        //0:未充电、1:充电
        "charge": await TsPlugin.isBatteryCharging() ? 1 : 0,
        //设备状态，0：正常、1：异常
        "deviceStatus": 0,
        //设备异常标签，正常、代理、异常、模拟器、root、无SIM
        "deviceTag": await TsPlugin.getRiskInfo(),
        //操作系统版本
        "osVersion": (await TsPlugin.getSystemCode()) == 2
            ? await TsPlugin.getHarmonyVersion()
            : await TsPlugin.getSystemVersion(),
        //设备分辨率
        "downloadChannel": await TsPlugin.getChannel(),
        "carrier": await TsPlugin.getSimOperator(), //设备运营商，0：移动、1：联通、2：电信,
        "uaWebView": await TsPlugin.getWebViewUserAgent(),
        "uaApp": await TsPlugin.getAppUserAgent(),
        "imei": await TsPlugin.getImei(),
        //"meid": await TsPlugin.getPhoneMEID(),
        "meid": "",
        "deviceId": await TsPlugin.getDeviceId(),
        "deviceApps": "",
      };
      KLog.d("AppConfigLog appInstall $map");
      var result = await HttpUtils.post<ConfigBean>(
        Api.appInstall,
        data: map,
        fromJsonT: (json) => ConfigBean.fromJson(json),
      );
      if (result.isSucceed) {
        //保存配置
        UserSp.instance.saveAppConfig(infoEntity: result.data);
      }
      return result;
    } catch (e) {
      KLog.d("AppConfigLog e ${e.toString()}");
      return null;
    }
  }

  ///IP
  Future<ResponseModel> ipRisk() async {
    var result = await HttpUtils.get(
      Api.ipRisk,
    );
    return result;
  }

  ///反馈接口
  Future<ResponseModel> afterSalesForm(Map<String, String> feedback) async {
    var result1 = await HttpUtils.post(
      Api.afterSalesForm,
      data: feedback,
    );
    return result1;
  }

  ///反馈问题列表
  Future<ResponseModel> vipIssuesList() async {
    var result1 = await HttpUtils.get(
      Api.vipIssuesList,
    );
    return result1;
  }


  //商品列表接口
  Future<ResponseModel<List<ProductInfoBean>>> itemsNewPage(
      {required int page}) async {
    var result1 = await HttpUtils.get(
      Api.itemsNewPage,
      params: {
        "page": page, //页数
        "pageSize": "20",
      },
      fromListJsonT: (e) => getProductInfoBean(e),
    );
    return result1;
  }


  Future<ResponseModel<List<CookbookBean>>> getCookbookCategory() async {
    var result1 = await HttpUtils.get(
      Api.cookbookCategory,
      fromListJsonT: (e) => getCookbookBean(e),
    );
    return result1;
  }

  //菜谱列表
  Future<ResponseModel<List<RecipeSearchBean>>> getCookbookSearch(Map<String, String> map) async {
    var result1 = await HttpUtils.post(
      Api.cookbookSearch,
      data: map,
      fromListJsonT: (e) => getRecipeSearchBean(e),
    );
    return result1;
  }

  //微信登录
  Future<ResponseModel> wxLogin(String code) async {
    var result1 = await HttpUtils.post(
      Api.wxLogin,
      data: {
        "appId": AppConst.djAppId,
        "code": code,
        "djId": UserSp.instance.configBean?.djId??""
      },
    );
    return result1;
  }



  //天气数据
  Future<ResponseModel<FreeBean>> free(String cityId) async {
    var result1 = await HttpUtils.get(
      Api.free,
      params: {
        "cityId": cityId,
      },
      fromJsonT: (json) => FreeBean.fromJson(json),
    );
    return result1;
  }

  //获取城市信息
  Future<ResponseModel> cityList(String cityName) async {
    var result = await HttpUtils.get(
      Api.cityList,
      params: {"cityName": cityName},
    );
    return result;
  }

  Future<ResponseModel> lifePro(String cityName) async {
    var result = await HttpUtils.get(
      Api.lifePro,
      params: {"cityId": cityName},
    );
    return result;
  }
}
